﻿namespace ElisVK.Data
{
    using System;
    using System.Collections.Generic;
    using System.Web;
    using Utils.Parsing;

    public class Album
    {
        private List<Audio> _songs;

        public int ID { get; set; }

        public String Name { get; set; }

        public List<Audio> Songs
        {
            get
            {
                return this._songs ?? (this._songs = new List<Audio>());
            }
            set
            {
                this._songs = value;
            }
        }


        public override string ToString()
        {
            return Name;
        }

        public static List<Album> ParseAlbumsPost(String page)
        {
            const string StartTag = "albums\":{";
            var albums = new List<Album>();
            var indexStart = page.IndexOf(StartTag);
            
            if (indexStart == -1)
                return albums;

            indexStart += StartTag.Length;

            var indexEnd = page.IndexOf("}}", indexStart + 1);
            
            if (indexEnd == -1)
                return albums;

            var all = page.Substring(indexStart, indexEnd - indexStart);

            //String[] items = all.Split(new char[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries).Where(z => z.Length > 1).ToArray();
            var items = TextParseTools.Split(all, new[] { "{", "}" }, "\"", false);

            foreach (string t in items)
            {
                //String[] fields = items[i].Split(',',':');
                var fields = TextParseTools.Split(t, new[] { ",", ":" }, "\"", false);

                if (fields.Length <= 3)
                    continue;

                var album = new Album();
                //album.id = fields[1];

                int id;
                if (!Int32.TryParse(TextParseTools.RemoveStartEndChars(fields[1]), out id))
                    continue;

                album.ID = id;
                album.Name = HttpUtility.HtmlDecode(TextParseTools.RemoveStartEndChars(fields[3]));

                albums.Add(album);
            }

            return albums;
        }

    }
}
